/*************************************************
*created by anchengan in 2024years 08months 06days
*This program is used to start autoai_master
*************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <sys/socket.h>

//check if IP valid
int isValidIP(char *ip){
    struct sockaddr_in sa;
    int result=inet_pton(AF_INET,ip,&(sa.sin_addr));
    return result != 0;
}

//check if PORT valid
int isValidPORT(char *port){
    for(int i=0;port[i]!='\0';i++){
        if(!isdigit(port[i])){
            return 0;
        }
    }
    int portNum=atoi(port);
    return portNum>0 && portNum<=65535;
}
int main(int argc,char *argv[]){
    if (argc !=3){
        fprintf(stderr,"Usage:%s <IP address> <port>\n",argv[0]);
        exit(EXIT_FAILURE);
    }
    char *ip = argv[1];
    char *port = argv[2];
    if (!isValidIP(ip)){
        fprintf(stderr,"Invalid IP address:%s\n",ip);
        exit(EXIT_FAILURE);
    }
    if (!isValidPORT(port)){
        fprintf(stderr,"Invalid port number:%s\n",port);
        exit(EXIT_FAILURE);
    }


    char clear_command[256];
    sprintf(clear_command,"kill -9 $(ps -aux |grep [a]utoai_master_run |grep %s |grep %s |awk '{print $2}') > /dev/null 2>&1",ip,port);
    system(clear_command);
    char start_command[256];
    sprintf(start_command,"%s_master_run %s %s",argv[0],argv[1],argv[2]);
    system(start_command);
}
